import pymysql
import config
import pymysql
from hashlib import sha1


connection = pymysql.connect(**config.MYSQL)
cursor = connection.cursor()


def hash_sha1(data):
    """生成字符串的hash值"""
    return sha1(data.encode("utf8")).hexdigest()


class MysqlUtil(object):

    @staticmethod
    def create(sql):
        """创建表格"""
        try:
            cursor.execute(sql)
        except Exception as e:
            print(f"创建表失败, 错误：{e}, 语句：{sql}")
            connection.rollback()
            return config.FUNC_CODE_ERROR

    @staticmethod
    def insert(sql, values):
        """插入数据/修改数据"""
        try:
            cursor.execute(sql, tuple(values))
            connection.commit()
        except Exception as e:
            print(f"插入数据/修改数据报错，错误:{e}")
            connection.rollback()
            return config.FUNC_CODE_ERROR

    @staticmethod
    def updata(sql):
        """修改数据"""
        try:
            cursor.execute(sql)
            connection.commit()
        except Exception as e:
            print(f"插入数据/修改数据报错，错误:{e},语句:{sql}")
            connection.rollback()
            return config.FUNC_CODE_ERROR

    @staticmethod
    def query(sql):
        """查询数据"""
        try:
            cursor.execute(sql)
            connection.commit()
            return cursor.fetchall()
        except Exception as e:
            print(f"查询数据报错，错误:{e},语句:{sql}")
            connection.rollback()
            return config.FUNC_CODE_ERROR

